/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;

using Anculus.Core;

using Galaxium.Gui;

namespace Galaxium.GStreamer
{
	public class GStreamerVideoBackend : IVideoBackend
	{
		List<GStreamerWebcamDevice> _devices = new List<GStreamerWebcamDevice> ();
		internal static List<GStreamerVideoPlayer> _activePlayers = new List<GStreamerVideoPlayer> ();
		
		public IEnumerable<IWebcamDevice> Devices
		{
			get { return _devices.ToArray (); }
		}
		
		public GStreamerVideoBackend ()
		{
			Gst.Initialize ();
			
			GetDevices ();
		}
		
		unsafe void GetDevices ()
		{
			_devices.Clear ();
			
			int num_devices;
			NativeGalaxiumWebcamDevice *devices = GStreamerInterop.gstreamer_video_get_devices (&num_devices);
			
			Log.Debug ("Found {0} webcam devices", num_devices);
			
			for (int i = 0; i < num_devices; i++)
			{
				GStreamerWebcamDevice device = new GStreamerWebcamDevice (devices[i]);
				bool hasFormats = false;
				
				foreach (IVideoFormat format in device.VideoFormats)
				{
					hasFormats = format != null; // Yeah, this is stupid but it shuts mcs up
					break;
				}
				
				if (hasFormats)
					_devices.Add (device);
				else
					Log.Warn ("Unable to use device '{0}', no video formats found", device.Name);
			}
		}
		
		public IVideoPlayer GetPlayer (IWebcamDevice device, IVideoFormat format)
		{
			foreach (GStreamerVideoPlayer player in _activePlayers)
			{
				// We can only use a device in one player at a time...
				
				if (player.Device == device)
				{
					player._references++;
					return player;
				}
			}
			
			return new GStreamerVideoPlayer (device as GStreamerWebcamDevice, format as GStreamerVideoFormat);
		}
	}
}
